from django.shortcuts import render
from rest_framework.response import Response

# Create your views here.

# 测试支付宝封装的包
from rest_framework.views import APIView
from libs.alipay_common import alipay, gateway
from utils.common_logger import logger
from utils.common_response import APIResponse

# class AliPyaView(APIView):
#     def get(self, request, *args, **kwargs):
#         res = alipay.api_alipay_trade_page_pay(
#             out_trade_no="20230393266602102102",
#             total_amount=1,
#             subject='性感内衣',
#             return_url="https://example.com",
#             notify_url="https://example.com/notify"
#         )
#         pay_url = gateway + res
#         return APIResponse(pay_url=pay_url)


from .serialzier import PaySerializer
from rest_framework.viewsets import GenericViewSet, ViewSet
from .models import Order

# 127.0.0.1:8000/api/v1/order/pay/  ---->post
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated


class PayOrderView(GenericViewSet):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = PaySerializer

    def create(self, request, *args, **kwargs):
        ser = self.get_serializer(context={'request': request}, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        pay_url = ser.context.get('pay_url')
        return APIResponse(msg='保存成功', pay_url=pay_url)


class SuccessView(ViewSet):
    # 要不要加认证类
    def get(self, request):
        # 我们前端的请求
        try:
            out_trade_no = request.query_params.get('out_trade_no')
            Order.objects.get(out_trade_no=out_trade_no, order_status=1)
            return APIResponse()
        except Exception as e:
            return APIResponse(code=101, msg='订单未支付')

    def post(self, request, *args, **kwargs):
        try:
            result_data = request.data.dict()  # 支付宝发送post请求给我们---》数据携带再请求体中---》urlencoded--》request.data不是字典格式，使用dict做成字典格式
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign')
            from libs.alipay_common import alipay
            result = alipay.verify(result_data, signature)  # 验签通过表示是支付宝给的，不是别人伪造的
            # trade_status 确认订单付款成功了
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')  # 必须这样，不能有别的东西
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')
